<?php
/*
* @Created by Phpstorm
* @User: Zhangxinlei
* @Date: 
* @Time:
*/

declare (strict_types = 1);
namespace app\common\service;


use think\facade\Session;
use think\facade\Cookie;
use think\facade\Request;
use think\facade\Db;
use app\common\model\AdminAdmin as M;
use app\common\validate\AdminAdmin as V;

class AdminAdmin
{
    public static function goPermission($data,$id)
    {
        if($data){
            Db::startTrans();
            try{
                //清除原有的直接权限
                Db::name('admin_admin_permission')->where('admin_id',$id)->delete();
                //填充新的直接权限
                foreach ($data as $v){
                    Db::name('admin_admin_permission')->insert([
                        'admin_id' => $id,
                        'permission_id' => $v,
                    ]);
                }
                Db::commit();
            }catch (DbException $exception){
                Db::rollback();
                return ['msg'=>'操作失败'.$e->getMessage(),'code'=>201];
            }
        }
    }
    /**
     * @param array $data
     * 用户登录验证
     */
    public static function login(array $data)
    {
        //验证规则
        $validate = new V();

        if(!$validate->scene('login')->check($data))
            return ['msg'=>$validate->getError(),'code'=>201];

        //验证用户
        $admin = M::where([
            'username' => trim($data['username']),
            'password' => set_password(trim($data['password'])),
            'status' => 1
        ])->find();

        if(!$admin) return ['msg'=>'用户名密码错误','code'=>201];
        //microtime(true)直接返回当前微秒的时间戳形式

        $admin->token = rand_string().$admin->id.microtime(true);

        $admin->save();

        //是否记住密码
        $time = 3600;


        if (isset($data['remember'])) $time = 30 * 86400;
//        halt($admin->id);
//

        //缓存登录信息
        $info = [
            'id' => $admin->id,
            'token' => $admin->token,
            'menu' => M::permissions($admin->id,Request::root())
        ];



        Session::set('admin', $info);
        Cookie::set('token',$admin->token, $time);
        // 触发登录成功事件
        event('AdminLog');
        return ['msg'=>'登录成功'];

    }
    /**
     *判断是否登录
     */
    public static function isLogin()
    {
        if(Session::get('admin')) return true;
        if(Cookie::has('token')){
            $admin = M::where(['token'=>Cookie::get('token'),'status'=>1])->find();
            if(!$admin) return false;
            return Session::set('admin',[
                'id' => $admin->id,
                'token' => $admin->token,
                'menu' => M::permissions($admin->id,Request::root())
            ]);
        }
        return false;
    }
    /**
     * 退出登录
     */
    public static function logout()
    {
        Session::delete('admin');
        Cookie::delete('token');
        Cookie::delete('sign');
        return ['msg'=>'退出成功'];
    }



}